//
//  ShoppingViewController.m
//  JewelryStore
//
//  Created by apple on 2016/11/1.
//  Copyright © 2016年 com. All rights reserved.
//

#import "ShoppingViewController.h"
#import "ShoppingDetailViewController.h"
#import "ShoppingPlacholderCell.h"
#import "ShopHeadView.h"
#import "ShoppingOneTableViewCell.h"
#import "ShoppingCollectViewCell.h"
#import "ShopBottomView.h"
#import "StatusModel.h"
#import "NSMutableArray+Tool.h"

#define SHOPCELL @"shoppingItemOne"
#define SHOPITEM @"shoppingCollectView"
#define SHOPPLACHOLDER @"placholder"
#define SHOPHEAD @"head"
#define COLLECTVIEW_HEIGHT SCREEN_WIDTH/1.8*3 + 10
#define ISALLSLECTED [self.statusArray isAllSlected]

@interface ShoppingViewController ()<UITableViewDelegate, UITableViewDataSource, MGSwipeTableCellDelegate, ShopBottomViewDelegate, ShoppingOneCollectionViewCellDelegate>

@property (nonatomic, strong) UITableView *shoppingTable;
@property (nonatomic, strong) NSMutableArray *shopModel;

@property (nonatomic, strong) UICollectionView *recomedCollect;
@property (nonatomic, strong) NSMutableArray *recomedModel;

@property (nonatomic, strong) ShopBottomView *bottomView;
@property (nonatomic, strong) NSMutableArray *statusArray;

@property (nonatomic, assign) CGFloat tempMoney;   //上一次的总价
@property (nonatomic, assign) CGFloat reslutMoney;
@property (nonatomic, assign) int resultNum;
@property (nonatomic, strong) ShoppingOneTableViewCell *temCell;


@end

@implementation ShoppingViewController

#pragma mark - cycle life

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;

    [self cofigureUI];
}

- (void)cofigureUI
{
    [self.view addSubview:self.shoppingTable];
    
    [self.view addSubview:self.recomedCollect];
    
    [self.view addSubview:self.bottomView];
}


#pragma mark - lazy

- (UITableView *)shoppingTable
{
    if (!_shoppingTable) {
        
        CGRect frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-45-SCREEN_WIDTH/5.5-64);
        
        _shoppingTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        
        _shoppingTable.delegate = self;
        
        _shoppingTable.dataSource = self;
        
        _shoppingTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _shoppingTable.backgroundColor = RGB(242, 243, 247);
        
        [_shoppingTable registerNib:[UINib nibWithNibName:@"ShoppingOneTableViewCell" bundle:nil] forCellReuseIdentifier:SHOPCELL];
        
        [_shoppingTable registerNib:[UINib nibWithNibName:@"ShoppingCollectViewCell" bundle:nil] forCellReuseIdentifier:SHOPITEM];
        
        [_shoppingTable registerNib:[UINib nibWithNibName:@"ShoppingPlacholderCell" bundle:nil] forCellReuseIdentifier:SHOPPLACHOLDER];
        
        [_shoppingTable registerNib:[UINib nibWithNibName:@"ShopHeadView" bundle:nil] forHeaderFooterViewReuseIdentifier:SHOPHEAD];
    }
    return _shoppingTable;
}

- (NSMutableArray *)shopModel
{
    if (!_shopModel) {
        
        _shopModel = [NSMutableArray arrayWithArray:@[@"", @"", @"", @"", @"", @""]];
    }
    return _shopModel;
}

- (ShopBottomView *)bottomView
{
    if (!_bottomView) {
        
        CGRect frame = CGRectMake(0, SCREEN_HEIGHT-49-SCREEN_WIDTH/5.5, SCREEN_WIDTH, SCREEN_WIDTH/5.5);

        _bottomView = [[ShopBottomView alloc] initWithFrame:frame];
        
        _bottomView.delegate = self;
        
        }
    return _bottomView;
}

- (NSMutableArray *)statusArray
{
    if (!_statusArray) {
        
        StatusModel *model1 = [[StatusModel alloc] init];
        
        StatusModel *model2 = [[StatusModel alloc] init];
        
        StatusModel *model3 = [[StatusModel alloc] init];
        
        StatusModel *model4 = [[StatusModel alloc] init];
        
        StatusModel *model5 = [[StatusModel alloc] init];
        
        StatusModel *model6 = [[StatusModel alloc] init];
        
        _statusArray = [NSMutableArray arrayWithArray:@[model1, model2, model3, model4, model5, model6]];
    }
    return _statusArray;
}

#pragma mark - table delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? (self.shopModel.count > 0 ? self.shopModel.count : 1) : 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? 0 : SCREEN_WIDTH/8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.section == 0 ? (_shopModel.count > 0 ? SCREEN_WIDTH/2 : SCREEN_HEIGHT/2) : COLLECTVIEW_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    if (indexPath.section == 0) {
        
        if (self.shopModel.count > 0)
        {
            ShoppingOneTableViewCell *pCell = [tableView dequeueReusableCellWithIdentifier:SHOPCELL];
            
            pCell.delegate = self;
            
            pCell.oneDelegate = self;
            
            pCell.tag = indexPath.row;
            
            //选中状态
            [self setupCellStatus:pCell];
            
            //商品数量
            StatusModel *model = self.statusArray[indexPath.row];
            
            pCell.shopNum = model.number;
            
            cell = pCell;
            
        }else
        {
            ShoppingPlacholderCell *pCell = [tableView dequeueReusableCellWithIdentifier:SHOPPLACHOLDER];
            
            cell = pCell;
        }
    }else
    {
        ShoppingCollectViewCell *pCell = [tableView dequeueReusableCellWithIdentifier:SHOPITEM];
        
        pCell.block = ^(NSIndexPath *indexPath)
        {
            [self gotoDetailViewController];
        };
    
        cell = pCell;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ShopHeadView *head = [tableView dequeueReusableHeaderFooterViewWithIdentifier:SHOPHEAD];
    
    head.contentView.backgroundColor = RGB(242, 243, 247);
    
    return head;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && self.shopModel.count > 0)
    {
        [self gotoDetailViewController];
    }
}

- (void)gotoDetailViewController
{
    ShoppingDetailViewController *detail = [[ShoppingDetailViewController alloc] init];
    
    [self.navigationController pushViewController:detail animated:YES];

}

#pragma mark - MGSwipeTableCellDelegate

- (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
{
    TT_Log(@"%ld", (long)index);
    
    if (index == 0) {
    
        //delete
        [_shopModel removeObjectAtIndex:cell.tag];
        
        [_statusArray removeObjectAtIndex:cell.tag];
        
        [_shoppingTable reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        
        [self updateBottomViewUI];
    
    }else
    {
        TT_Log(@"已收藏");
    }
    return YES;
}

#pragma mark - ShopBottomView delegate

- (void)selectAllCell
{
    [self.statusArray selectAllStatus];
    
    [self.shoppingTable reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
    [self updateBottomViewUI];
}

#pragma mark - ShoppingOneCollectionViewCell delegate

- (void)selectOrCancel:(ShoppingOneTableViewCell *)cell
{
    //改变单个选中状态
    [self.statusArray changeSelectStauts:cell.tag];
    
    [self.shoppingTable reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:cell.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    
    //计算选中总价
    [self calculateSelectedCellTotalPrice:cell];
    
    //改变全选状态
    self.bottomView.block(ISALLSLECTED, _reslutMoney, _resultNum);

}

- (void)calculateItemTotalPrice:(ShoppingOneTableViewCell *)cell total:(int)num case:(int)type
{
    //改变单个数量
    [self calculateForSelectedCellChangeNumber:cell num:num type:type];
    
    TT_Log(@"%f", _reslutMoney);
    
    self.bottomView.block(CHANGEKEEPSTATUS, _reslutMoney, _resultNum);

}

#pragma mark - private Method

- (void)updateBottomViewUI
{
    _reslutMoney = [_statusArray calculateTotalPriceOfSelectedCell];
    
    _resultNum = [_statusArray calculateTotalNumOfSelectedCell];
    
    self.bottomView.block(ISALLSLECTED, _reslutMoney, _resultNum);
    
}

- (void)calculateSelectedCellTotalPrice:(ShoppingOneTableViewCell *)cell
{
    StatusModel *model = self.statusArray[cell.tag];
    
    if ([self.statusArray isSlectedCell:cell.tag]) {
        
        _reslutMoney += model.totalPrice;
        
        _resultNum += model.number;
        
    }else
    {
        _reslutMoney -= model.totalPrice;
        
        _resultNum -= model.number;
    }

}

- (void)calculateForSelectedCellChangeNumber:(ShoppingOneTableViewCell *)cell num:(int) num type:(int)type
{
    StatusModel *model = self.statusArray[cell.tag];
 
    model.number = num;
    
    if ([self.statusArray isSlectedCell:cell.tag])
    {
        if (type == AddType) {
            
            _reslutMoney += model.price;
            
            _resultNum += 1;
        }else
        {
            if (!(cell.shopNum == 1)) {
                
                _reslutMoney -= model.price;
                
                _resultNum -= 1;
            }
        }
        
    }

}

- (void)setupCellStatus:(ShoppingOneTableViewCell *)cell
{
    if ([self.statusArray isSlectedCell:cell.tag])
    {
        [cell setupBtnSelect];
    }else
    {
        [cell setupBtnNone];
    }

}
@end
